import { getHistoryAppointments, addAppointment, getValidAppointments } from "@/api/reservations";
import { Message } from "element-ui";

const appointment = {
    namespaced: true,
    state: {
        allAppointments: null,
        historyAppointments: null,
        historyIds: null
    },
  
    getters: {
    },
  
    mutations: {
      SET_DATA: (state, payload) => { // 从localStorage同步
        console.log("SET_DATA", state, payload);
        state.historyAppointments = null; 
        state.historyIds = null;
        state.allAppointments = null;
      },
      SET_HISTORY: (state, historyAppointments) => {
        state.historyAppointments = historyAppointments;
        state.historyIds = [];
        historyAppointments.forEach((historyAppointment)=>{
          state.historyIds.push(historyAppointment.alid);
        })
      },
      SET_ALLAPPOINTMENT: (state, allAppointments) => {
        state.allAppointments = allAppointments;
      },
      ADD_HISTORY: (state, historyAppointment) => {
        console.log("ADD_HISTORY");
        state.historyAppointments.push(historyAppointment);
        state.historyIds.push(historyAppointment.alid);
        for(var i=0;i<state.allAppointments.length;i++) {
          var element = state.allAppointments[i];
          if (element.alid == historyAppointment.alid) {
            element.currentNumber += 1;
          }
        }
      }
    },
  
    actions: {
        refresh_history: (context)=>{
          console.log("refresh history appointment");
          getHistoryAppointments()
          .then((res) => {
            context.commit("SET_HISTORY", res);
          })
        },
        make_appointment: (context, limitId)=>{
          console.log("make an appointment, limitId:" + limitId);
          addAppointment(limitId)
          .then(res=>{
            console.log(res);
            Message.success("预约成功");
            context.commit("ADD_HISTORY", res);
          })
        },
        refresh_all_appointment: (context, queryParam)=>{
          console.log("refresh all appointment");
          getValidAppointments(queryParam)
          .then((res) => {
            context.commit("SET_ALLAPPOINTMENT", res);
          })
        }
    }
  
  };
  
  export default appointment;
  